package com.dy.yunying.biz.service.cps.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dy.yunying.api.cps.dto.DataReportDto;
import com.dy.yunying.api.cps.vo.DataReportVO;
import com.dy.yunying.api.entity.ChannelManageDO;
import com.dy.yunying.api.entity.WanGameChannelInfoDO;
import com.dy.yunying.api.entity.WanGameDO;
import com.dy.yunying.api.resp.WanGameRes;
import com.dy.yunying.biz.config.YunYingProperties;
import com.dy.yunying.biz.dao.cps.DataReportDao;
import com.dy.yunying.biz.dao.manage.ChannelManageDOMapper;
import com.dy.yunying.biz.dao.manage.WanGameChannelInfoMapper;
import com.dy.yunying.biz.dao.manage.WanGameDOMapper;
import com.dy.yunying.biz.service.cps.DataReportService;
import com.dy.yunying.biz.service.manage.AdRoleGameService;
import com.dy.yunying.biz.service.manage.AdRoleUserService;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.service.PigUser;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import jodd.introspector.MapperFunction;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author leisw
 * @date 2022/9/15 11:20
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DataReportServiceImpl implements DataReportService {

	private final DataReportDao dailyDataDao;

	private final AdRoleUserService adRoleUserService;

	private final WanGameDOMapper wanGameDOMapper;

	private final ChannelManageDOMapper channelManageDOMapper;

	private final WanGameChannelInfoMapper wanGameChannelInfoMapper;

	private final  AdRoleGameService adRoleGameService;


	@Resource
	private YunYingProperties yunYingProperties;


	@Override
	public R count(DataReportDto req) {
		try{
			// 当前用户
			final PigUser user = SecurityUtils.getUser();
			List<Integer> ownerRoleUserIds = adRoleUserService.getOwnerRoleUserIds();
			// 当前账号及管理的账号
			List<Integer> roleUserIdList = new ArrayList<>();
			req.setRoleUserIdList(roleUserIdList);
			roleUserIdList.add(user.getId());
			roleUserIdList.addAll(ownerRoleUserIds);

			// 判断是否管理员
			if (SecurityUtils.getRoles().contains(yunYingProperties.getRoleId())) {
				req.setIsSys(1);
			}
			//当前用户游戏权限
			if (StringUtils.isEmpty(req.getGameIdArr())){
				List<WanGameRes> ownerRoleGames = adRoleGameService.getOwnerRoleGames();
				if (CollectionUtils.isNotEmpty(ownerRoleGames)){
					List<String> collect = ownerRoleGames.stream().map(new MapperFunction<WanGameRes, String>() {
						@Override
						public String apply(WanGameRes wanGameRes) {
							return wanGameRes.getId().toString();
						}
					}).collect(Collectors.toList());
					if (CollectionUtils.isNotEmpty(collect)){
						req.setGameIdArr(String.join(",",collect));
					}
				}
			}
			return R.ok(dailyDataDao.count(req));
		}catch (Exception e){
			log.error("cps数据报表条数查询异常：{}",e);
			return R.failed("cps数据报表条数查询失败...");
		}

	}

	@Override
	public R<List<DataReportVO>> page(DataReportDto req) {
		List<DataReportVO> list;
		try {
			// 当前用户
			final PigUser user = SecurityUtils.getUser();
			List<Integer> ownerRoleUserIds = adRoleUserService.getOwnerRoleUserIds();
			// 当前账号及管理的账号
			List<Integer> roleUserIdList = new ArrayList<>();
			req.setRoleUserIdList(roleUserIdList);
			roleUserIdList.add(user.getId());
			roleUserIdList.addAll(ownerRoleUserIds);

			// 判断是否管理员
			if (SecurityUtils.getRoles().contains(yunYingProperties.getRoleId())) {
				req.setIsSys(1);
			}
			//当前用户游戏权限
			if (StringUtils.isEmpty(req.getGameIdArr())){
				List<WanGameRes> ownerRoleGames = adRoleGameService.getOwnerRoleGames();
				if (CollectionUtils.isNotEmpty(ownerRoleGames)){
					List<String> collect = ownerRoleGames.stream().map(new MapperFunction<WanGameRes, String>() {
						@Override
						public String apply(WanGameRes wanGameRes) {
							return wanGameRes.getId().toString();
						}
					}).collect(Collectors.toList());
					if (CollectionUtils.isNotEmpty(collect)){
						req.setGameIdArr(String.join(",",collect));
					}
				}
			}
			list = dailyDataDao.list(req);
			deal(list,req);
		} catch (Exception e) {
			log.error("cps数据报表查询异常：{}",e);
			return R.failed("cps数据报表查询失败...");
		}
		return R.ok(list);
	}

	@Override
	public R<List<DataReportVO>> collect(DataReportDto req) {
		try{

			// 当前用户
			final PigUser user = SecurityUtils.getUser();
			List<Integer> ownerRoleUserIds = adRoleUserService.getOwnerRoleUserIds();
			// 当前账号及管理的账号
			List<Integer> roleUserIdList = new ArrayList<>();
			req.setRoleUserIdList(roleUserIdList);
			roleUserIdList.add(user.getId());
			roleUserIdList.addAll(ownerRoleUserIds);

			// 判断是否管理员
			if (SecurityUtils.getRoles().contains(yunYingProperties.getRoleId())) {
				req.setIsSys(1);
			}
			//当前用户游戏权限
			if (StringUtils.isEmpty(req.getGameIdArr())){
				List<WanGameRes> ownerRoleGames = adRoleGameService.getOwnerRoleGames();
				if (CollectionUtils.isNotEmpty(ownerRoleGames)){
					List<String> collect = ownerRoleGames.stream().map(new MapperFunction<WanGameRes, String>() {
						@Override
						public String apply(WanGameRes wanGameRes) {
							return wanGameRes.getId().toString();
						}
					}).collect(Collectors.toList());
					if (CollectionUtils.isNotEmpty(collect)){
						req.setGameIdArr(String.join(",",collect));
					}
				}
			}

			Long count = dailyDataDao.count(req);
			if (count == 0) {
				return R.ok(new ArrayList<>());
			}
			List<DataReportVO> list=dailyDataDao.list(req);
			deal(list,req);
			return R.ok(list);
		}catch (Exception e){
			log.error("cps数据报表汇总查询异常：{}",e);
			return R.failed("cps数据报表汇总数据查询失败...");
		}
	}


	private void deal(List<DataReportVO> data, DataReportDto req) {
		if (!CollectionUtils.isEmpty(data)){
			if(StringUtils.isNotBlank(req.getQueryColumn())){
				// 填充子游戏名称
				if (StringUtils.contains(req.getQueryColumn(), "app_code")) {
					List<Long> codeList = data.stream().map(DataReportVO::getAppCode).distinct().filter(Objects::nonNull).collect(Collectors.toList());
					Map<Long, String> mapping = codeList.isEmpty() ? Collections.emptyMap() : wanGameDOMapper.selectList(Wrappers.<WanGameDO>lambdaQuery().select(WanGameDO::getId, WanGameDO::getGname).in(WanGameDO::getId, codeList)).stream().collect(Collectors.toMap(WanGameDO::getId, WanGameDO::getGname, (k1, k2) -> k1));
					data.forEach(e -> e.setGameName(StringUtils.defaultIfBlank(mapping.get(e.getAppCode()), "-")));
				}

				// 填充子渠道名称
				if (StringUtils.contains(req.getQueryColumn(), "chl_sub")) {
					List<String> codeList = data.stream().map(DataReportVO::getChlSub).distinct().filter(StringUtils::isNotEmpty).collect(Collectors.toList());
					Map<String, String> mapping = codeList.isEmpty() ? Collections.emptyMap() : channelManageDOMapper.selectList(Wrappers.<ChannelManageDO>lambdaQuery().select(ChannelManageDO::getChncode, ChannelManageDO::getChnname).in(ChannelManageDO::getChncode, codeList).ne(ChannelManageDO::getPid, NumberUtils.INTEGER_ZERO)).stream().collect(Collectors.toMap(ChannelManageDO::getChncode, ChannelManageDO::getChnname, (k1, k2) -> k1));
					data.forEach(e -> e.setChlName(StringUtils.defaultIfBlank(mapping.get(e.getChlSub()), "-")));
				}

				// 填充分包渠道名称
				if (StringUtils.contains(req.getQueryColumn(), "chl_app")) {
					final List<String> codeList = data.stream().map(DataReportVO::getChlApp).distinct().filter(StringUtils::isNotEmpty).collect(Collectors.toList());
					LambdaQueryWrapper<WanGameChannelInfoDO> queryWrapper = Wrappers.<WanGameChannelInfoDO>lambdaQuery().select(WanGameChannelInfoDO::getChl, WanGameChannelInfoDO::getCodeName).in(WanGameChannelInfoDO::getChl, codeList);
					Map<String, String> appchlMap = wanGameChannelInfoMapper.selectList(queryWrapper).stream().collect(Collectors.toMap(WanGameChannelInfoDO::getChl, WanGameChannelInfoDO::getCodeName, (k1, k2) -> k1));
					data.forEach(e -> e.setChlAppName(StringUtils.defaultIfBlank(appchlMap.get(e.getChlApp()), e.getChlApp())));
				}
			}
			for (DataReportVO dailyDataVO : data) {
				if(StringUtils.isBlank(dailyDataVO.getGameName())){
					dailyDataVO.setGameName("-");
				}
				if(StringUtils.isBlank(dailyDataVO.getChlName())){
					dailyDataVO.setChlName("-");
				}
				if(StringUtils.isBlank(dailyDataVO.getChlAppName())){
					dailyDataVO.setChlAppName("-");
				}
				dailyDataVO.setAccountNumRate(dailyDataVO.getAccountNumRate()+"%");
				dailyDataVO.setNewpayRate(dailyDataVO.getNewpayRate()+"%");
				dailyDataVO.setAccountpayRate(dailyDataVO.getAccountpayRate()+"%");
			}
		}

	}
}

